import ctypes
import PySimpleGUI as sg
import subprocess
import os

# 设置DPI感知
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(2)
except AttributeError:
    ctypes.windll.user32.SetProcessDPIAware()

class WinQuickJumpTool:
    BUTTON_CONFIGS = {
        '快速功能': [
            {'text': '设备管理器', 'cmd': 'devmgmt.msc'},
            {'text': '打印机', 'cmd': 'ms-settings:printers'},
            {'text': '凭据管理器', 'cmd': 'control /name Microsoft.CredentialManager'},
            {'text': '安全中心', 'cmd': 'ms-settings:windowsdefender'},
            {'text': '网络适配器', 'cmd': 'ncpa.cpl'},
            {'text': '设置-网络', 'cmd': 'ms-settings:network-status'},
            {'text': '>网络工具', 'method': 'get_ip_info'},
            {'text': '飞行模式', 'cmd': 'ms-settings:proximity'},
            {'text': '共享管理', 'cmd': 'fsmgmt.msc'},
            {'text': '本地共享', 'cmd': '\\\\localhost'},
            {'text': '访问共享', 'method': 'to_shared'},
            {'text': '断开共享访问', 'method': 'del_net_use'},
            {'text': '控制面板', 'cmd': 'control.exe'},
            {'text': '注册表编辑器', 'cmd': 'regedit'},
            {'text': '服务', 'cmd': 'services.msc'},
            {'text': '任务管理器', 'cmd': 'taskmgr'}
        ],
        '优化': [
            {'text': '关闭预留空间', 'cmd': 'DISM /Online /Set-ReservedStorageState /State:Disabled'},
            {'text': '关闭设备加密', 'method': 'close_bitlocker'},
            {'text': '禁用sysMain', 'method': 'dis_sys_main'},
            {'text': '禁用WSearch', 'method': 'ban_wsearch'},
            {'text': '解除程序风险警告', 'method': 'remove_program_warning'},
            {'text': '手动更新', 'method': 'manual_update'},
            {'text': '显示扩展名', 'method': 'show_file_extensions'},
            {'text': '右键管理员打开', 'method': 'add_admin_open'}
        ]
    }

    def __init__(self, buttons_per_row=5):
        # 设置每行按钮数量
        self.buttons_per_row = buttons_per_row
        # 设置主题和字体
        sg.theme('Default1')  # 修改为主题列表中的其他主题
        self.font = ('Microsoft YaHei', 9)
        
        # 创建主窗口
        self.create_main_window()

    def create_main_window(self):
        # 定义所有按钮配置
        self.button_configs = self.BUTTON_CONFIGS

        # 创建选项卡布局
        tabs = []
        for tab_name, buttons in self.button_configs.items():  # 改为使用self.button_configs
            # 每 self.buttons_per_row 个按钮分为一行
            rows = []
            for i in range(0, len(buttons), self.buttons_per_row):
                row_buttons = []
                for btn in buttons[i:i+self.buttons_per_row]:
                    key = f'-{btn["text"].upper().replace(" ", "_")}-'
                    if 'cmd' in btn:
                        row_buttons.append(sg.Button(btn['text'], key=key, font=self.font))
                    else:
                        row_buttons.append(sg.Button(btn['text'], key=key, font=self.font))
                rows.append(row_buttons)
            tabs.append(sg.Tab(tab_name, rows))
        
        layout = [[sg.TabGroup([tabs])]]
        self.window = sg.Window('Win快速跳转工具 v1.3.6 by谪仙', layout, finalize=True)
    
    def run(self):
        while True:
            event, values = self.window.read()
            if event == sg.WIN_CLOSED:
                break
            
            if event.startswith('-') and event.endswith('-'):
                print(f"处理按钮事件: {event}")  # 添加日志
                # 使用self.button_configs访问配置
                for tab_name, buttons in self.button_configs.items():
                    for btn in buttons:
                        key = f'-{btn["text"].upper().replace(" ", "_")}-'
                        if event == key:
                            if 'cmd' in btn:
                                self.run_command(btn['cmd'])
                            elif 'method' in btn:
                                method = getattr(self, btn['method'])
                                method()
        
        self.window.close()
    
    def run_command(self, cmd):
        try:
            print(f"执行命令: {cmd}")
            if cmd.startswith(("ms-settings:", "\\\\")):
                subprocess.run(f'start "" {cmd}', shell=True, check=True)
            elif cmd.endswith('.cpl'):
                # 特殊处理.cpl控制面板项
                subprocess.run(f'control.exe {cmd}', shell=True, creationflags=subprocess.CREATE_NO_WINDOW)
            elif cmd.endswith('.msc'):
                # 特殊处理.msc管理控制台项
                subprocess.run(cmd, shell=True, creationflags=subprocess.CREATE_NO_WINDOW)
            elif cmd.startswith('control'):
                subprocess.run(cmd, shell=True, creationflags=subprocess.CREATE_NO_WINDOW)
            else:
                subprocess.run(cmd, shell=True, check=True)
        except subprocess.CalledProcessError as e:
            error_msg = f"命令执行失败(返回码 {e.returncode})"
            print(error_msg)
            sg.popup_error(error_msg, title="执行错误")
        except Exception as e:
            error_msg = f"执行错误: {str(e)}"
            print(error_msg)
            sg.popup_error(error_msg, title="执行错误")

    def close_bitlocker(self):
        """关闭设备加密"""
        try:
            subprocess.run('manage-bde -off C:', shell=True, check=True)
            sg.popup_quick_message("已关闭设备加密", auto_close_duration=2)
        except Exception as e:
            sg.popup_error(f"关闭设备加密失败: {str(e)}")

    def dis_sys_main(self):
        """禁用sysMain服务"""
        self._manage_service('SysMain', 'stop', 'disable')

    def ban_wsearch(self):
        """禁用Windows Search服务"""
        self._manage_service('WSearch', 'stop', 'disable')

    def remove_program_warning(self):
        """解除程序风险警告"""
        try:
            subprocess.run('reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Associations" /v "LowRiskFileTypes" /t REG_SZ /d ".exe" /f', shell=True)
            sg.popup_quick_message("已解除程序风险警告", auto_close_duration=2)
        except Exception as e:
            sg.popup_error(f"操作失败: {str(e)}")

    def _manage_service(self, name, action, config):
        """管理Windows服务"""
        try:
            subprocess.run(f'net {action} {name}', shell=True, check=True)
            subprocess.run(f'sc config {name} start= {config}', shell=True, check=True)
            sg.popup_quick_message(f"已{action}并{config}服务{name}", auto_close_duration=2)
        except Exception as e:
            sg.popup_error(f"服务操作失败: {str(e)}")

    def manual_update(self):
        """手动检查Windows更新"""
        try:
            subprocess.run('start ms-settings:windowsupdate-action', shell=True)
            sg.popup_quick_message("已打开Windows更新设置", auto_close_duration=2)
        except Exception as e:
            sg.popup_error(f"打开更新设置失败: {str(e)}")

    def show_file_extensions(self):
        """显示文件扩展名"""
        try:
            subprocess.run('reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "HideFileExt" /t REG_DWORD /d 0 /f', shell=True)
            sg.popup_quick_message("已启用文件扩展名显示", auto_close_duration=2)
        except Exception as e:
            sg.popup_error(f"设置失败: {str(e)}")

    def add_admin_open(self):
        """添加右键管理员打开菜单"""
        try:
            subprocess.run('reg add "HKCR\*\shell\runas" /ve /d "管理员打开" /f', shell=True)
            subprocess.run('reg add "HKCR\*\shell\runas" /v "HasLUAShield" /d "" /f', shell=True)
            subprocess.run('reg add "HKCR\*\shell\runas\command" /ve /d "cmd.exe /c start \"\" \"%1\"" /f', shell=True)
            sg.popup_quick_message("已添加右键管理员打开菜单", auto_close_duration=2)
        except Exception as e:
            sg.popup_error(f"添加右键菜单失败: {str(e)}")

if __name__ == "__main__":
    app = WinQuickJumpTool()
    app.run()